package com.link510.aitools.activity.airobot.audio;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;
import android.widget.SeekBar;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.google.common.base.Strings;
import com.link510.aitools.R;
import com.link510.aitools.core.listen.CWMListener;
import com.link510.aitools.core.message.MessageInfo;
import com.link510.aitools.framework.activity.BaseAcitivity;
import com.link510.aitools.services.Airobots;
import com.link510.aitools.services.QiniuUtils;
import com.link510.aitools.services.CustomWaitDialogUtils;
import com.link510.aitools.services.XFCouldUtils;
import com.orhanobut.logger.Logger;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 语音转文字
 */
public class RobotAudioEditActivity extends BaseAcitivity {

    private CustomWaitDialogUtils customWaitDialogUtils;

    private File audioFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot_audio_edit);
        initUI();
    }

    @BindView(R.id.word_edit_text)
    public EditText wordEditText;

    @BindView(R.id.audo_speed_seekbar)
    public SeekBar audoSpeedSeekbar;

    @BindView(R.id.audo_pitch_seekbar)
    public SeekBar audoPitchSeekbar;

    @BindView(R.id.audo_volume_seekbar)
    public SeekBar audoVolumeSeekbar;

    private String voiceCode = "";

    @OnClick(R.id.xiaoyanRadioButton)
    public void xiaoyanRadioButtonClick() {
        this.voiceCode = "xiaoyan";
    }


    @OnClick(R.id.aisjiuxuRadioButton)
    public void aisjiuxuRadioButtonClick() {
        this.voiceCode = "aisjiuxu";
    }

    @OnClick(R.id.aisxpingRadioButton)
    public void aisxpingRadioButtonClick() {
        this.voiceCode = "aisxping";
    }

    @OnClick(R.id.aisjingerRadioButton)
    public void aisjingerRadioButtonClick() {
        this.voiceCode = "aisjinger";
    }

    @OnClick(R.id.aisbabyxuRadioButton)
    public void aisbabyxuRadioButtonClick() {
        this.voiceCode = "aisbabyxu";
    }


    @OnClick(R.id.create_button)
    public void createButtonClick() {

        final String word = wordEditText.getText().toString();

        if (Strings.isNullOrEmpty(word)) {
            ToastUtils.showShort("请输入转换的文字");
            return;
        }

        new Thread(() -> {


            // 将“12345678”替换成您申请的APPID，申请地址：http://www.xfyun.cn
            // 请勿在“=”与appid之间添加任何空字符或者转义符

            mHandler.sendEmptyMessageDelayed(101, 10 * 1000);

            int audoSpeed = audoSpeedSeekbar.getProgress();
            int audoPitch = audoPitchSeekbar.getProgress();
            int audoVolume = audoVolumeSeekbar.getProgress();


            XFCouldUtils.getInstance(getApplicationContext()).speaking(word,
                    this.voiceCode,
                    audoSpeed,
                    audoPitch,
                    audoVolume,
                    new CWMListener<String>() {
                        @Override
                        public void onSuccess(String message, String ttsAudioPath) {

                            mHandler.removeMessages(101);

                            File audioFile = new File(ttsAudioPath);
                            if (!audioFile.exists()) {
                                ToastUtils.showShort("语音转换失败");
                                return;
                            }

                            RobotAudioEditActivity.this.audioFile = audioFile;
                            ToastUtils.showShort(message);

                        }

                        @Override
                        public void onError(int code, String message) {
                            ToastUtils.showShort(message);
                        }
                    });
        }).start();
    }

//    @OnClick(R.id.play_button)
//    public void playButtonClick() {
//        XFCouldUtils.getInstance(mContext).stopSpeaking();
//    }

    @OnClick(R.id.send_button)
    public void editButtonClick() {

        if (audioFile == null) {
            ToastUtils.showShort("请先录音");
            return;
        }

        if (!audioFile.exists()) {
            ToastUtils.showShort("语音转换失败");
            return;
        }
        toUploadAction(audioFile);
    }

    private void initUI() {
        customWaitDialogUtils = new CustomWaitDialogUtils(this.mContext);
    }


    /**
     * 文件上传
     *
     * @param file 上传
     */
    public void toUploadAction(File file) {

        if (file == null) {
            ToastUtils.showShort("文件不能为空");
            return;
        }


        if (!file.exists()) {
            ToastUtils.showShort("文件不存在");
            return;
        }

        customWaitDialogUtils.show("文件上传中...");

        mHandler.sendEmptyMessageDelayed(100, 10 * 3000);
        QiniuUtils.getInstance().upload(file, new CWMListener<String>() {
            @Override
            public void onSuccess(String message, String mp3Url) {

                mHandler.removeMessages(100);

                if (Strings.isNullOrEmpty(mp3Url)) {
                    customWaitDialogUtils.close();
                    ToastUtils.showShort("文件上传失败");
                    return;
                }

                customWaitDialogUtils.show("文件上传中成功...");
                Logger.e("文件上传成功:" + mp3Url);
                Logger.e("文件上传成功:" + JSON.toJSONString(file.getAbsoluteFile()));

                customWaitDialogUtils.show("命令发送中...");
                Airobots.getInstance().audioEditUrl(RobotAudioEditActivity.this.deviceSN, mp3Url, new CWMListener<MessageInfo<String>>() {

                    /**
                     * 解析成功
                     * <p>
                     * * @param message 消息
                     *
                     * @param message message
                     * @param messageInfo 实体消息
                     */
                    @Override
                    public void onSuccess(String message, MessageInfo<String> messageInfo) {
                        customWaitDialogUtils.close();
                        ToastUtils.showShort("命令下发成功");
                    }

                    /**
                     * 返回错误解析
                     *
                     * @param code    错误状态码
                     *                * @param message 消息
                     * @param message message
                     */
                    @Override
                    public void onError(int code, String message) {

                        customWaitDialogUtils.close();
                        ToastUtils.showShort("命令下发成功");
                    }
                });

            }

            @Override
            public void onError(int code, String message) {
                customWaitDialogUtils.close();
                ToastUtils.showShort(message);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (customWaitDialogUtils != null) {
            customWaitDialogUtils.dismiss();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message mas) {
            switch (mas.what) {
                case 0:
                    //此处进行UI的更新
                    break;
                case 100:
                    RobotAudioEditActivity.this.customWaitDialogUtils.close();
                    ToastUtils.showShort("上传失败");
                    break;
                case 101:
                    RobotAudioEditActivity.this.customWaitDialogUtils.close();
                    ToastUtils.showShort("语音合成失败");
                    break;
            }
        }
    };

}